package com.film.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.film.common.util.DataTimeUtil;
import com.film.dao.LeavingMessageMapper;
import com.film.dao.UserMapper;
import com.film.pojo.LeavingMessage;
import com.film.pojo.User;
import com.film.pojo.vo.ActiveUserV0;
import com.film.pojo.vo.LeavingMessageV0;
import com.film.service.LeavingMessageService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class LeavingMessageServiceImpl implements LeavingMessageService {
    @Autowired
    private LeavingMessageMapper leavingMessageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void save(LeavingMessage leavingMessage) {
        leavingMessage.setCreateAt(DataTimeUtil.getNowTimeString());//调用DataUtil类的getNowTimeString方法设置创建时间
        leavingMessageMapper.insert(leavingMessage);
    }

    @Override
    public void reply(LeavingMessage leavingMessage) {
        leavingMessageMapper.updateById(leavingMessage);
    }

    @Override
    public List<LeavingMessageV0> findAll() {
        List<LeavingMessage> list = leavingMessageMapper.selectList(null);
        List<LeavingMessageV0> result = new ArrayList<>();
        for (LeavingMessage m: list) {
            User user = (User) userMapper.selectById(m.getUid());
            result.add(new LeavingMessageV0(m.getId(), m,user));
        }
        return result;
    }

    @Override
    public List<ActiveUserV0> findActiveUsers() {
        List<ActiveUserV0> result = new ArrayList<>();
        List<User> users = userMapper.selectList(null);
        for (User user : users){
            ActiveUserV0 activeUserV0 = new ActiveUserV0();
            activeUserV0.setUser(user);
            activeUserV0.setNumber(leavingMessageMapper.selectList(
                    new QueryWrapper<LeavingMessage>().in("uid", user.getId())).size());
            result.add(activeUserV0);
        }
        //按留言数量排序
        result.sort((v1,v2)->v2.getNumber().compareTo(v1.getNumber()));
        return result;
    }
}
